const util = require('../../../../utils/util.js');
const api = require('../../../../config/api.js');
const user = require('../../../../services/user.js');
const { $Message } = require('../../../../lib/iview/base/index');

import Dialog from '../../../../ucenter/lib/vant/dialog/dialog';

const app = getApp();

Page({
  data: {
    vipshow: false,
    authenticationShow: false,
    logininfo: {},
    posters: { "isupload": false, "ip": "", "url": "", "isupdate": false, "size": 0 },
    upimg: '',
  },
  onLoad: function (options) {
  },
  onReady: function () {
    this.setData({
      logininfo: app.globalData.logininfo,
      openid: app.globalData.logininfo.openid
    });
  },
  onShow: function () {
    var _this = this
    _this.setData({
      logininfo: app.globalData.logininfo
    });
    var openid = app.globalData.logininfo.openid;
    var data = {};
    var posters = _this.data.posters;
    var isupdate = posters.isupdate;
    var isload = posters.isupload;
    var ip = posters.ip
    var imgurl = posters.url
    console.log(posters)
    if (isupdate == true) {
      if (isload == true) { 
        if (_this.data.upimg == 3){
          wx.uploadFile({
            url: api.File_doImageUpload,
            filePath: imgurl,
            name: 'file',
            formData: {
              "type": 7
            },
            success(res) {
              var data = JSON.parse(res.data);
              if (data.code == 200) {
                var ip = data.result.ip;
                var path = data.result.path;
                if (openid != null && openid != "") {
                  util.post(api.fetchToken()).then(function (res) {
                    if (res.access_token != '') {
                      return Promise.resolve({
                        access_token: res.access_token
                      });
                    }
                  }).then(function (res) {
                    data.openid = openid;
                    data.access_token = res.access_token;
                    data.param = JSON.stringify({ "ip": ip, "url": path })
                    util.post(api.UpdateBackgroundPath, data).then(function (res) {
                      if (res.code == 200) {
                        var logininfo = app.globalData.logininfo;logininfo.userInfo.backgroundip = ip;
logininfo.userInfo.backgroundpath = path;
                        wx.setStorage({
                          key: 'logininfo',
                          data: logininfo
                        })
                        _this.setData({
                          logininfo: app.globalData.logininfo,
                        })
                      }
                    });
                  });
                }
              } 
            },
          })
        }
        if (_this.data.upimg == 4) {
          wx.uploadFile({
            url: api.File_doImageUpload,
            filePath: imgurl,
            name: 'file',
            formData: {
              "type": 8
            },
            success(res) {
              var data = JSON.parse(res.data);
              if (data.code == 200) {
                var ip = data.result.ip;
                var path = data.result.path;
                if (openid != null && openid != "") {
                  util.post(api.fetchToken()).then(function (res) {
                    if (res.access_token != '') {
                      return Promise.resolve({
                        access_token: res.access_token
                      });
                    }
                  }).then(function (res) {
                    data.openid = openid;
                    data.access_token = res.access_token;
                    data.param = JSON.stringify({ "ip": ip, "url": path })
                    util.post(api.UpdateStorehbPath, data).then(function (res) {
                      if (res.code == 200) {
                        var logininfo = app.globalData.logininfo;
                        logininfo.userInfo.storehbip = ip;
                                                logininfo.userInfo.storehbpath = path;
                        wx.setStorage({
                          key: 'logininfo',
                          data: logininfo
                        })
                        _this.setData({
                          logininfo: app.globalData.logininfo,
                        })
                      }
                    });
                  });
                }
              }
            },
          })
        }
      } else {
        if (_this.data.upimg==3){
          if (openid != null && openid != "") {
            util.post(api.fetchToken()).then(function (res) {
              if (res.access_token != '') {
                return Promise.resolve({
                  access_token: res.access_token
                });
              }
            }).then(function (res) {
              data.openid = openid;
              data.access_token = res.access_token;
              data.param = JSON.stringify({ "ip": ip, "url": imgurl})
              util.post(api.UpdateBackgroundPath, data).then(function (res) {
                if (res.code == 200) {
                  var logininfo = app.globalData.logininfo;
                  logininfo.userInfo.backgroundip = ip;
                  logininfo.userInfo.backgroundpath = imgurl;
                  wx.setStorage({
                    key: 'logininfo',
                    data: logininfo
                  })
                  _this.setData({
                    logininfo: app.globalData.logininfo,
                  })
                }
              });
            });
          }
        }
        if (_this.data.upimg == 4) {
          if (openid != null && openid != "") {
            util.post(api.fetchToken()).then(function (res) {
              if (res.access_token != '') {
                return Promise.resolve({
                  access_token: res.access_token
                });
              }
            }).then(function (res) {
              data.openid = openid;
              data.access_token = res.access_token;
              data.param = JSON.stringify({ "ip": ip, "url": imgurl })
              util.post(api.UpdateStorehbPath, data).then(function (res) {
                if (res.code == 200) {
                  var logininfo = app.globalData.logininfo;
                  logininfo.userInfo.storehbip = ip;
                  logininfo.userInfo.storehbpath = imgurl;
                  wx.setStorage({
                    key: 'logininfo',
                    data: logininfo
                  })
                  _this.setData({
                    logininfo: app.globalData.logininfo,
                  })
                }
              });
            });
          }
        }
      }
    }
  },
  onHide: function () {
  },
  onUnload: function () {
  },

  onUserInfoClick: function () {
    if (wx.getStorageSync('token')) {

    } else {
      this.showLoginDialog();
    }
  },

  showLoginDialog() {
    this.setData({
      showLoginDialog: true
    })
  },

  onCloseLoginDialog() {
    this.setData({
      showLoginDialog: false
    })
  },

  onDialogBody() {
    // 阻止冒泡
  },

  onSectionItemClick: function (event) {

  },
  onChange(event) {
    this.setData({
      activeNames: event.detail
    });
  },

  onTagChange(event) {
    const detail = event.detail;
    this.setData({
      ['tags[' + event.detail.name + '].checked']: detail.checked
    })
  },
  oneChange(event) {
    this.setData({
      'oneChecked': event.detail.checked
    })
  },
  doExtra(event) {
    this.setData({
      selectcard: event.currentTarget.id,
      visible2: true
    });
  },
  onShareAppMessage() {
    return {
      title: 'handshake Weapp',
      imageUrl: 'https://image.xingqubaike.com:8443/my/24hour.png'
    };
  },
  /*onChange(event) {
    const detail = event.detail;
    this.setData({
      ['tags[' + event.detail.name + '].checked']: detail.checked
    })

  },*/
  enterPerson: function (e) {
    wx.navigateTo({
      url: '../personhome/personhome?userid=1'
    })
  },
  doPublish: function (event) {
    wx.navigateTo({
      url: 'publish/publish?userid=1',
    })
  },
  doAvatar: function (event) {
    /*wx.navigateTo({
      url: '../../../lib/cropper/cropper1/index?userid=1',
    })*/

    var _this = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        wx.navigateTo({
          url: 'avatar/index?imageSrc=' + res.tempFilePaths[0],
        })
      },
    })
  },
  domessage: function (event) {
    wx.navigateTo({
      url: '../../chat/chat?userid=1',
    })
  },
  dostoresetup: function (event) {
    wx.navigateTo({
      url: 'store/store?userid=1',
    })
    console.log("进入店铺设置")
  },
  dohomesetup: function (event) {
    wx.navigateTo({
      url: 'homesetup/homesetup?userid=1',
    })
    console.log("进入主页设置")
  },
  doupdatename: function (event) {
    var _this = this;

    let akind = event.currentTarget.dataset.name;
    let updatename = event.detail.value.replace(/\s+/g, '');
    if (updatename.length>0){
      let atitle = '';
      let param = {};
      if (akind == 'storename') {
        atitle = '修改店铺名';
        param = {
          "openid": app.globalData.logininfo.openid,
          "storename": updatename
        };
      }
      else if (akind == 'nickname') {
        atitle = '修改用户昵称';
        param = {
          "openid": app.globalData.logininfo.openid,
          "nickname": updatename
        };
      }

      wx.showLoading({
        title: atitle,
      })

      util.post(api.My_fetchTokenUrl).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        //console.log("res:" + res.accesstoken);

        if (res.access_token != '') {
          _this.setData({
            accesstoken: res.access_token
          });

          let url = api.My_doUpdatePersonInfo + "?access_token=" + _this.data.accesstoken;
          util.request(url, param, 'POST').then((res2) => {
            console.log(res2);

            if (akind == 'storename') {
              _this.data.logininfo.userInfo.storename = updatename;
            }
            else if (akind == 'nickname') {
              _this.data.logininfo.userInfo.nickName = updatename;
            }

            wx.setStorage({
              key: 'logininfo',
              data: _this.data.logininfo
            });

            wx.hideLoading();
          }).catch((err) => {
            wx.hideLoading();

            console.log(err);
            console.log("保存信息错误!");
          });
        }
        else {
          console.log("error accesstoken!");
        }
      }).catch((err) => {
        wx.hideLoading();

        console.log(err);
      });
    }else{
      wx.showToast({
        title: '不能为空',
        icon: 'none'
      })
    }
  },
  //更换用户头像
  douseravatar: function (event) {
    var _this = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        wx.navigateTo({
          url: 'avatar/index?atype=user&imageSrc=' + res.tempFilePaths[0],
        })
      },
    })
    console.log("头像选择")
  },
  //更换店铺LOGO
  dostoreavatar: function (event) {
    var _this = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        wx.navigateTo({
          url: 'avatar/index?atype=store&imageSrc=' + res.tempFilePaths[0],
        })
      },
    })
    console.log("店铺LOGO选择")
  },
  dobackground: function (event) {
    var _this = this
    wx.navigateTo({
      url: '../../../pages/background/background?type=3&title=设置个人主页海报',
    })
    _this.setData({
      upimg: 3
    })
    console.log("主页背景选择")
  },
  dostorehb: function (event) {
    var _this = this
    wx.navigateTo({
      url: '../../../pages/background/background?type=4&title=设置店铺海报',
    })
    _this.setData({
      upimg: 4
    })
    console.log("店铺海报选择")
  },
  doauth: function (event) {
    var _this = this

    Dialog.alert({
      title: '圈主身份认证提醒',
      message: '尊敬的兴趣百科用户，您身份认证，即将到期。为了防止您的功能特权缺失，请尽快操作晋级，以防功能权限受到限制。'
    }).then(() => {
      // on close
    });
    console.log("身份认证")
  },
  //显示VIP介绍
  openVipShow: function () {
    this.setData({
      vipshow: true
    })
  },
  //显示认证介绍
  openAuthenticationShow: function(){
    this.setData({
      authenticationShow: true
    })
  },
  //关闭VIP介绍
  closeVipShow: function () {
    this.setData({
      vipshow: false,
      authenticationShow: false,
    })
  },
  onPullDownRefresh() {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();

    var that = this;

    // 隐藏导航栏加载框
    wx.hideNavigationBarLoading();
    // 停止下拉动作
    wx.stopPullDownRefresh();
  },
  /**
   * 跳转身份认证
   */
  gotoAuthentication: function(){
    wx.navigateTo({
      url: '/grade/pages/grade/authentication/authentication',
    })
  },
  /**
   * 跳转晋级VIP
   */
  gotoPromotedVIP: function () {
    wx.navigateTo({
      url: '/grade/pages/grade/promotedVIP/promotedVIP',
    })
  },
})